package com.jxit0573.android.lib.net;

import android.util.Log;

import com.jxit0573.android.lib.BuildConfig;
import com.jxit0573.android.lib.util.JsonUtils;

import java.util.Map;

import okhttp3.RequestBody;

/**
 * @author jia
 */
@SuppressWarnings("AlibabaAbstractClassShouldStartWithAbstractNaming")
public abstract class OkHttpRequest {

    protected String url;
    protected Object tag;
    protected Map<String, String> headers;
    protected Map<String, Object> params;
    protected okhttp3.Request.Builder builder = new okhttp3.Request.Builder();

    protected OkHttpRequest(String url, Object tag, Map<String, String> headers, Map<String, Object> params) {
        this.url = url;
        this.tag = tag;
        this.headers = headers;
        this.params = params;
        if (BuildConfig.DEBUG) {
            Log.e("接口请求参数", JsonUtils.toJson(params));
        }
        initBuilder();
    }

    private void initBuilder() {
        if (headers != null) {
            headers.forEach((k, v) -> builder.addHeader(k, v));
        }
        builder.url(url).tag(tag);
    }

    /**
     * 构建RequestBody对象
     *
     * @return RequestBody对象
     */
    protected abstract RequestBody buildRequestBody();

    /**
     * 构建Request对象
     *
     * @param requestBody RequestBody对象
     * @return Request对象
     */
    protected abstract okhttp3.Request buildRequest(RequestBody requestBody);

    protected okhttp3.Request generateRequest() {
        return buildRequest(buildRequestBody());
    }

    public RequestCall build() {
        return new RequestCall(this);
    }

}
